<template>
  <div class="one-index-content">
    <div class="setting-content">
      <p class="data-statistic-title">多指标可视化展示</p>
      <el-button class="detail-tile" type="primary" plain @click="handleIndicatorCet"
        >设置指标</el-button
      >
    </div>


    <div v-if='listData==null || listData.length == 0'
      class="setting-content"
      style="border: none; background: #fff; color: #61a3c8; margin-top: 20px"
    >
      <p class="data-statistic-title">暂无设置指标，可联系项目申办人/负责人进行设置</p>
    </div>
<!--    <div v-if='listData==null || listData.length == 0' class="setting-content" style="border: none; background: #fff; margin-top: 20px">
      <p class="data-statistic-title">实例展示</p>
      <p class="detail-tile">实例仅做效果展示，图中数据不作为真实数据</p>
    </div>-->


    <div class="chart-list" v-loading="chartLoading">
      <div
        :ref="el => setChartRef(el, index)"
        class="chart"
        v-for="(item, index) in getChartInfoList"
        :key="index"
      ></div>
    </div>
    <el-dialog
      v-model="isIndicatorSet"
      title="指标设置"
      top="5vh"
      width="1200"
      body-class="QR-code-dialog-body"
      @close="closeIndicatorSet"
    >
      <indicatorSet ref="indicatorSetRef" />
    </el-dialog>
  </div>
</template>
<script setup>
import * as echarts from 'echarts';
import indicatorSet from './indicatorSet.vue';
import { getChartInfo, getList } from '@/api/multipleindicators/multipleIndicators';
import { useStore } from 'vuex';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const crud = ref(null);
const store = useStore();
const selectTab = ref(1);
const routerQuery = ref({});
routerQuery.value = route.query;

let chartLoading = ref(false);
let isIndicatorSet = ref(false);
let indicatorSetRef = ref(null);

let listData = ref(null);

const handleIndicatorCet = () => {
  isIndicatorSet.value = true;
};
let getChartInfoList = ref([]);
const initGetList = () => {
  let values = {
    descs: 'create_time',
     trial:routerQuery.value.trialId,
  };
  chartLoading.value = true;
  getList(1, 200, values).then(res => {
     listData = res.data.data.records;
    // 创建一个数组，存储所有的异步请求
    const chartInfoPromises = listData.map(item => {
      return getChartInfo(item.id); // 返回 Promise
    });

    Promise.all(chartInfoPromises)
      .then(allData => {
        // 重置图表列表
        getChartInfoList.value = [];
        // 假设每个图表数据包含 chartType 和对应的数据数组
        allData.forEach((DATA, index) => {
          // 从 listData 中获取对应的 chartType
          const chartType = listData[index].chartType;
          const name = listData[index].name;
          getChartInfoList.value.push({
            chartType: chartType, // 使用从 listData 获取的 chartType
            data: DATA.data.data, // 根据实际API结构调整
            title:name,
          });
        });
        chartLoading.value = false;
        initChart();
      })
      .catch(console.error);
  });
};

// 存储图表实例和 DOM 引用的响应式数组
const chartRefs = ref([]);
const chartInstances = ref([]);
// 动态绑定 ref 的方法
const setChartRef = (el, index) => {
  chartRefs.value[index] = el;
};
const initChart = () => {
  nextTick(() => {
    // 清理旧图表实例
    chartInstances.value.forEach(instance => instance && instance.dispose());
    chartInstances.value = [];
    console.log('getChartInfoList.value', getChartInfoList.value);
    getChartInfoList.value.forEach((item, index) => {
      const el = chartRefs.value[index];
      if (!el) return;

      let option;
      switch (item.chartType) {
        case '1': // 柱状图
          option = createBarOption(item.data,item.title);
          break;
        case '2': // 饼图
          option = createPieOption(item.data,item.title);
          break;
        case '3': // 折线图
          option = createLineOption(item.data,item.title);
          break;
      }

      const chartInstance = echarts.init(el);
      chartInstance.setOption(option);
      chartInstances.value[index] = chartInstance;
    });
  });
};

// 柱状图配置
const createBarOption = (data,titleName) => {
  const xData = data.map(d => d.option);
  const seriesData = data.map(d => d.selectionNum);
  return {
    tooltip: {
      show: true,
      formatter: function (params) {
        return params.name + '：' + params.value;
      },
    },
    xAxis: { type: 'category', data: xData },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: seriesData, barWidth: 20 }],
    title: {
      text: titleName, // 标题文本
      left: "center",     // 标题位置（left/center/right）
      textStyle: {        // 标题样式
        color: "#333",    // 字体颜色
        fontSize: 16,     // 字体大小
        fontWeight: "bold" // 字体粗细
      },
      padding: [10, 0]    // 标题内边距
    }
  };
};

// 饼图配置
const createPieOption = (data,titleName) => {
  const seriesData = data.map(d => ({
    value: d.proportion,
    name: d.option,
    selectionNum: d.selectionNum,
  }));
  return {
    tooltip: {
      show: true,
      formatter: function (params) {
        return (
          params.name +
          '：' +
          params.data.selectionNum +
          '（' +
          Math.floor(Number(params.value) * 100) +
          '%）'
        );
      },
    },
    series: [
      {
        type: 'pie',
        data: seriesData,
        radius: '50%',
        emphasis: { itemStyle: { shadowBlur: 10 } },
      },
    ],
    title: {
      text: titleName, // 标题文本
      left: "center",     // 标题位置（left/center/right）
      textStyle: {        // 标题样式
        color: "#333",    // 字体颜色
        fontSize: 16,     // 字体大小
        fontWeight: "bold" // 字体粗细
      },
      padding: [10, 0]    // 标题内边距
    }
  };
};

// 折线图配置
const createLineOption = (data,titleName) => {
  const xData = data.map(d => d.option);
  const seriesData = data.map(d => d.selectionNum);
  return {
    tooltip: {
      show: true,
      formatter: function (params) {
        return params.name + '：' + params.value;
      },
    },
    xAxis: { type: 'category', data: xData },
    yAxis: { type: 'value' },
    series: [{ type: 'line', data: seriesData, smooth: true }],
    title: {
      text: titleName, // 标题文本
      left: "center",     // 标题位置（left/center/right）
      textStyle: {        // 标题样式
        color: "#333",    // 字体颜色
        fontSize: 16,     // 字体大小
        fontWeight: "bold" // 字体粗细
      },
      padding: [10, 0]    // 标题内边距
    }
  };
};

// 关闭指标设置弹窗事件
const closeIndicatorSet = () => {
  initGetList();
};

onMounted(() => {
  initGetList();
});

// 组件卸载时清理
onUnmounted(() => {
  chartInstances.value.forEach(instance => instance && instance.dispose());
});
</script>
<style scoped>
.one-index-content {
  width: 100%;
  height: calc(100% - 150px);
  /* overflow-y: auto; */
  display: flex;
  flex-direction: column;
}
.setting-content {
  border: 1px solid #3c8dbc;
  border-left-width: 5px;
  border-radius: 3px;
  padding: 0px 10px;
  background: #f2f7fa;
  display: flex;
  align-items: center;
}
.data-statistic-title {
  line-height: 36px;
  font-size: 16px;
  align-items: center;
  justify-content: center;
  margin: 0px;
}
.detail-tile {
  margin: 0px 10px;
  /* color: #777; */
  line-height: 36px;
  font-size: 13px;
}
.chart-list {
  width: 100%;
  height: auto;
  min-height: 300px;
  display: flex;
  flex-wrap: wrap;
}
.chart {
  width: 50%;
  height: 300px;
}
::v-deep .QR-code-dialog-body {
    height: 80vh;
    overflow-y: auto;
}
</style>
